import { getComponentCompileDir } from "../utils/commonUtils";
import path from "path";
import fs from "fs";
import * as vscode from "vscode";
import { openOrCreateCustomizedCommandsFile } from "./openOrCreateCustomizedCommandsFile";

/**
* Executes a customized command from the customizedCommands.json file
*/
export async function executeCustomizedCommand() {
   const componentCompileDir = getComponentCompileDir();
   const customizedCommandsFilePath = path.join(componentCompileDir, 'customizedCommands.json');
   
   // Check if the customizedCommands.json file exists
   if (!fs.existsSync(customizedCommandsFilePath)) {
       vscode.window.showErrorMessage('customizedCommands.json not found. Please configure your commands first.');
       // Open configuration
       openOrCreateCustomizedCommandsFile();
       return;
   }
   
   try {
       // Read and parse the customized commands file
       const fileContent = fs.readFileSync(customizedCommandsFilePath, 'utf8');
       const commandsConfig = JSON.parse(fileContent);
       
       // Check if there are any commands defined
       if (!commandsConfig.commands || commandsConfig.commands.length === 0) {
           vscode.window.showErrorMessage('No commands defined in customizedCommands.json. Please configure your commands first.');
           openOrCreateCustomizedCommandsFile();
           return;
       }
       
       // Create QuickPickItems from the commands
       const quickPickItems: vscode.QuickPickItem[] = commandsConfig.commands.map((cmd: any) => ({
           label: cmd.name,
           description: cmd.description || '',
           detail: cmd.command
       }));
       
       // Show QuickPick
       vscode.window.showQuickPick(quickPickItems, {
           placeHolder: 'Select a command to execute'
       }).then(selectedItem => {
           if (selectedItem && selectedItem.detail) {
               // Execute the selected command
               executeCustomCommand(selectedItem.detail);
           }
       });
   } catch (error) {
       vscode.window.showErrorMessage(`Failed to read customized commands: ${error instanceof Error ? error.message : String(error)}`);
   }
}

/**
* Executes a custom command as a VS Code task
* @param command The command to execute
*/
function executeCustomCommand(command: string) {
   const taskName = `Custom Command: ${command}`;
   
   const shellExecution = new vscode.ShellExecution(command, {
       executable: vscode.env.shell,
       shellArgs: ['-lic']
   });
   
   const task = new vscode.Task(
       { type: "shell" },
       vscode.TaskScope.Workspace,
       taskName,
       "Component Compile",
       shellExecution
   );
   
   // Execute the task
   vscode.tasks.executeTask(task).then(
       () => {
           console.log(`Custom command task started: ${command}`);
       },
       (error) => {
           console.error('Failed to start custom command task:', error);
           vscode.window.showErrorMessage(`Failed to execute command: ${error instanceof Error ? error.message : String(error)}`);
       }
   );
}